const mysql = require('mysql');
const config = require('../config');
module.exports = {
    connections: {}, // 连接集合

    // 连接
    async connect(mysqlKey, mysqlConf) {
        if (!(mysqlKey && mysqlConf)) {
            throw new Error('mysqlKey or mysqlConf is null');
        }

        if (this.connections[mysqlKey]) {
            const conn = this.connections[mysqlKey];
            try {
                await this.handleConnection(conn);
                return {code: 1, msg: `Connected to database as id ${conn.threadId}`};
            } catch (err) {
                throw new Error(`Error connecting to database: ${err.stack}`);
            }
        } else {
            const conn = mysql.createConnection({...mysqlConf});
            try {
                await this.handleConnection(conn);
                this.connections[mysqlKey] = conn;
                return {code: 1, msg: `Connected to database as id ${conn.threadId}`};
            } catch (err) {
                throw new Error(`Error connecting to database: ${err.stack}`);
            }
        }
    },

    // 关闭
    async close(mysqlKey) {
        if (!this.connections[mysqlKey]) {
            throw new Error(`No connection found for key ${mysqlKey}`);
        }

        let conn = this.connections[mysqlKey];
        try {
            await this.handleDisconnection(conn);
            return {code: 1, msg: `Database connection closed`};
        } catch (err) {
            throw new Error(`Error closing database connection: ${err.stack}`);
        }
    },

    getConnByKey(mysqlKey) {
        return this.connections[mysqlKey];
    },

    // 获取mysql的连接状态
    getState(mysqlKey) {
        return this.connections[mysqlKey]?.state;
    },

    async query(mysqlKey, {sql, values}) {
        if (!config.mysql) {
            return {code: 2, msg: 'mysql is close'};
        }

        const conn = this.getConnByKey(mysqlKey);
        if (!conn) {
            throw new Error(`No connection found for key ${mysqlKey}`);
        }

        try {
            const results = await this.executeQuery(conn, sql, values);
            return {code: 1, msg: `Query performed successfully`, data: results};
        } catch (error) {
            throw new Error(`Error performing query: ${error.stack}`);
        }
    },

    // 辅助函数 - 处理连接
    handleConnection(conn) {
        return new Promise((resolve, reject) => {
            conn.connect((err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    },

    // 辅助函数 - 处理断开连接
    handleDisconnection(conn) {
        return new Promise((resolve, reject) => {
            conn.end((err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    },

    // 辅助函数 - 执行查询
    executeQuery(conn, sql, values) {
        return new Promise((resolve, reject) => {
            conn.query(sql, values, (error, results, fields) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(results);
                }
            });
        });
    },
};
